import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    meta: {
      isNeedLogin: true
    },
    component: () => import('@/views/Layout'),
    children: [
      {
        path: '',
        component: () => import('@/views/Home')
      },
      {
        path: 'shop',
        name: 'shop',
        component: () => import('@/views/Shop'),
        children: [
          {
            path: 'brand/add',
            component: () => import('@/views/Shop/brand')
          },
          {
            path: 'express/add',
            component: () => import('@/views/Shop/express')
          },
          {
            path: 'cat/add',
            component: () => import('@/views/Shop/cat')
          }
        ]
      },
      {
        path: 'shop/list',
        name: 'shop-list',
        component: () => import('@/views/Shop/list')
      },
      {
        path: 'shop/add',
        component: () => import('@/views/Shop/addGoods')
      },
      {
        path: 'post',
        component: () => import('@/views/Post'),
        children: [
          {
            path: 'list',
            component: () => import('@/views/Post/list')
          },
          {
            path: 'add',
            component: () => import('@/views/Post/add')
          }
        ]
      }
    ]
  },
  {
    path: '/login',
    meta: {
      isNeedLogin: false
    },
    component: () => import('@/views/Login')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.isNeedLogin) {
    if (localStorage.getItem('user')) {
      next()
      return
    }
    next('/login')
    return
  }

  next()
})

export default router
